import random
import uuid
import requests
from typing import List, Dict
import json
from faker import Faker

fake = Faker(['zh_CN'])

def get_all_users(base_url: str, token: str) -> List[Dict]:
    """获取所有用户"""
    url = f"{base_url}/api/v1/user/get_all_users"
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    users = []
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            users = response.json()
            # 过滤掉admin用户
            users = [user for user in users if user['username'] != 'admin']
    except Exception as e:
        print(f"获取用户列表失败: {str(e)}")
    
    return users

def get_family_users(base_url: str, token: str) -> List[Dict]:
    """获取所有用户"""
    url = f"{base_url}/api/v1/user/get_all_users"
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    users = []
    try:
        response = requests.post(url, headers=headers)
        if response.status_code == 200:
            users = response.json()
            # 过滤掉admin用户
            users = [user for user in users if user['username'] != 'admin']
    except Exception as e:
        print(f"获取用户列表失败: {str(e)}")
    
    return users

def create_family(base_url: str, token: str) -> Dict:
    """创建家族"""
    url = f"{base_url}/api/v1/family/create"
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    family_data = {
        "family_id" : "e9d54447-3fa9-4018-9058-e2bffb764cbc",
        "family_name": f"{fake.last_name()}氏家族",
        "family_desc": fake.sentence(),
        "family_status": 1
    }
    
    try:
        response = requests.post(url, json=family_data, headers=headers)
        if response.status_code == 200:
            print(f"成功创建家族: {family_data['family_name']}")
            return response.json()
        else:
            print(f"创建家族失败: {response.status_code}")
            print(response.json())
            return None
    except Exception as e:
        print(f"创建家族时发生错误: {str(e)}")
        return None

def add_user_to_family(base_url: str, token: str, username: str, family_id: str):
    """将用户添加到家族"""
    url = f"{base_url}/api/v1/family/add_member"
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    data = {
        "username": username,
        "family_id": family_id
    }
    
    try:
        response = requests.post(url, json=data, headers=headers)
        if response.status_code == 200:
            print(f"成功将用户 {username} 添加到家族")
            return True
        else:
            print(f"添加用户到家族失败: {response.status_code}")
            print(response.json())
            return False
    except Exception as e:
        print(f"添加用户到家族时发生错误: {str(e)}")
        return False

def create_family_with_members(base_url: str, token: str, num_members: int = 10):
    """创建家族并添加成员"""
    # 获取所有用户
    users = get_all_users(base_url, token)
    if not users:
        print("没有获取到用户数据")
        return
    
    # 创建家族
    family = create_family(base_url, token)
    if not family:
        print("创建家族失败")
        return
    
    # 随机选择用户加入家族
    selected_users = random.sample(users, min(num_members, len(users)))
    success_count = 0
    
    for user in selected_users:
        if add_user_to_family(base_url, token, user['username'], family['family_id']):
            success_count += 1
    
    print(f"\n总结: 成功创建家族 {family['family_name']}，添加了 {success_count} 个成员")

if __name__ == "__main__":
    BASE_URL = "http://172.16.1.188:18000"
    TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9lbWFpbCI6Ind1d2VudDkzMEAxNjMuY29tIiwidXNlcl9waG9uZSI6IjE4MjI1ODg4MzgxIiwiZXhwIjoxNzM3NTY0ODE0fQ.Hgp6gKATPq10zxsQrRG6dyONWfRxr_oXFjSPdZtpiUk"
    
    create_family_with_members(BASE_URL, TOKEN, num_members=10) 